package com.xieyong.leetcode;

import java.util.ArrayList;
import java.util.List;

public class Leetcode1298 {
    public static void main(String[] args) {
        Leetcode1298 leetcode1298 = new Leetcode1298();
        int[] status = {1,0,1,0};
        int[] candies = {7,5,4,100};
        int[][] keys = {{},{},{1},{}};
        int[][] containedBoxes = {{1,2},{3},{},{}};
        int[] initialBoxes = {0};
        int i = leetcode1298.maxCandies(status, candies, keys, containedBoxes, initialBoxes);
        System.out.println(i);

    }

    public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initailBoxes) {
        int[][] boxesStatus = new int[status.length][3];
        List<Integer> initBoxesList = new ArrayList<>();
        for (int box : initailBoxes) {
            boxesStatus[box][1] = 1;
            initBoxesList.add(box);
        }
        int res = openBoxes(status, candies, keys, containedBoxes, initBoxesList,boxesStatus);
        return res;
    }

    private int openBoxes(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, List<Integer> boxes, int[][] boxesStatus) {
        if(boxes.isEmpty()){
            return 0;
        }
        int res = 0;
        List<Integer> nextBoxes = new ArrayList<>();
//        尝试打开所有盒子，并更新盒子和钥匙的拥有状态以及盒子的使用情况
        for(int curbox : boxes) {
//            判断是否可以打开当前盒子
            if(boxesStatus[curbox][0] == 0 && status[curbox] == 1) {
                boxesStatus[curbox][0] = 1; // 表示打开盒子
                res += candies[curbox];  // 获取糖果
                for(int j : containedBoxes[curbox]) {
                    boxesStatus[j][1] = 1;
                }
                for(int j : keys[curbox]) {
                    boxesStatus[j][2] = 1;
                }
            }
        }
//        更新盒子是否可以打开状态
        for(int i = 0; i < boxesStatus.length; i++) {
            if(boxesStatus[i][1] == 1 && boxesStatus[i][2] == 1) {
                status[i] = 1;
            }
//                找到当前拥有的可打开盒子
            if(boxesStatus[i][0] == 0 && boxesStatus[i][1] == 1 && status[i] == 1) {
                nextBoxes.add(i);
            }
        }
        res += openBoxes(status, candies, keys, containedBoxes, nextBoxes, boxesStatus);
        return res;
    }
}
